﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SimplePad.Plugins;
using SimplePad.Tools;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using SimplePad.Core;
using System.Collections;

namespace SimplePad
{
    public partial class MainForm : Form, IApplication
    {
        TextEditor txt;

        private bool _isClosing = false;

        public DockPanel getDockPanel()
        {
            return MainDock;
        }

        public MainForm()
        {
            InitializeComponent();

            LoggingService.Info("Load form position");

            GeometryFromString(SimplePad.Properties.Settings.Default.WindowGeometry, this);
            Skin.ApplySkinToForm(this);

            pnLoading.LoadingCircleControl.StylePreset = LoadingCircle.StylePresets.Firefox;
            pnLoading.LoadingCircleControl.Active = false;

            LoggingService.Info("Load plugins");

            Globals.PluginManager.LoadDefaultFileExtensions();
            Globals.PluginManager.AssemblyLoaded += PluginManager_AssemblyLoaded;
            Globals.PluginManager.LoadExtensions(Application.StartupPath + @"\plugins");

            LoggingService.Info("Run plugins");

            foreach (var plugin in Globals.PluginManager.Plugins)
            {
                plugin.Instance.initPlugin(this);
            }

            FilesManager.MainDockPanel = MainDock;

            LoggingService.Info("Load last files");

            loadLastOpenedFiles();
            loadSettings();
            SimplePad.Properties.Settings.Default.SettingsSaving += new System.Configuration.SettingsSavingEventHandler(onSettingsSaved);
        }

        public void loadLastOpenedFiles()
        {
            if (SimplePad.Properties.Settings.Default.OpenedFiles != null && SimplePad.Properties.Settings.Default.OpenedFiles.Count > 0)
            {
                foreach (DictionaryEntry file in SimplePad.Properties.Settings.Default.OpenedFiles)
                {
                    FilesManager.OpenFile(file.Value.ToString());
                }
            }
        }

        public void loadSettings()
        {
            if (SimplePad.Properties.Settings.Default.General != null && SimplePad.Properties.Settings.Default.General.Count > 0)
            {
                foreach (string settKey in SimplePad.Properties.Settings.Default.General.Keys)
                {
                    string settVal = SimplePad.Properties.Settings.Default.General[settKey];
                    switch (settKey)
                    {
                        case "maintoolbar.visible":
                            this.MainToolbar.Visible = bool.Parse(settVal);
                            break;
                        case "mainstatus.visible":
                            this.MainStatus.Visible = bool.Parse(settVal);
                            break;
                        case "mainmenu.visible":
                            this.MainMenu.Visible = bool.Parse(settVal);
                            break;
                    }
                }
            }
        }

        public void onSettingsSaved(object sender, EventArgs e)
        {
            if(_isClosing)
                return;

            loadSettings();
        }

        void PluginManager_AssemblyLoaded(object sender, AssemblyLoadedEventArgs e)
        {
            LoggingService.Info("Load plugin:" + e.Filename);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            var mng = new PluginManager<IPlugin, IPlugin>();

            mng.LoadDefaultFileExtensions();

            mng.LoadExtensions(Application.StartupPath + @"\plugins");
        }

        private void mnuOpen_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                FilesManager.OpenFile(dlg.FileName);
            }
        }

        private void mnuSave_Click(object sender, EventArgs e)
        {
            save();
        }

        private void save()
        {
            pnLoading.LoadingCircleControl.Active = true;
            pnLoading.LoadingCircleControl.Update();

            //TextEditor.save((((SimplePad.TextEditor)(MainTabs.SelectedItem))), (((SimplePad.TextEditor)(MainTabs.SelectedItem))).FileName);

            pnLoading.LoadingCircleControl.Active = false;
            pnLoading.LoadingCircleControl.Update();
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void mnuCopy_Click(object sender, EventArgs e)
        {
            var textArea = getCurrentTextArea();
            if (textArea.Document.ReadOnly)
            {
                return;
            }
            textArea.ClipboardHandler.Copy(null, null);
        }

        private void mnuCut_Click(object sender, EventArgs e)
        {
            var textArea = getCurrentTextArea();
            if (textArea.Document.ReadOnly)
            {
                return;
            }
            textArea.ClipboardHandler.Cut(null, null);
        }

        private void mnuPaste_Click(object sender, EventArgs e)
        {
            var textArea = getCurrentTextArea();
            if (textArea.Document.ReadOnly)
            {
                return;
            }
            textArea.ClipboardHandler.Paste(null, null);
        }

        private void TextEditor_TextChanged(object sender, EventArgs e)
        {
            //mnuUndo.Enabled = TextEditor.EnableUndo;
            //mnuRedo.Enabled = TextEditor.EnableRedo;
        }

        private void mnuUndo_Click(object sender, EventArgs e)
        {
            //TextEditor.Undo();
        }

        private void mnuRedo_Click(object sender, EventArgs e)
        {
            //TextEditor.Redo();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //Notification.Show();
            //Notification.Flash(4);
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            if (txt != null)
            {
                txt.Notification.Show();
            }
        }

        private void cmnuToLowerCase_Click(object sender, EventArgs e)
        {
            txt.toLowerCase();
        }

        private void cmnuToUperCase_Click(object sender, EventArgs e)
        {
            txt.toUperCase();
        }

        private ICSharpCode.TextEditor.TextArea getCurrentTextArea()
        {
            return null;
            //return (((SimplePad.TextEditor)(MainTabs.SelectedItem))).Editor.ActiveTextAreaControl.TextArea;
        }

        #region Geometry
        private static bool GeometryIsBizarreSize(Size size)
        {
            return (size.Height <= Screen.PrimaryScreen.WorkingArea.Height &&
                size.Width <= Screen.PrimaryScreen.WorkingArea.Width);
        }

        private static bool GeometryIsBizarreLocation(Point loc, Size size)
        {
            bool locOkay;
            if (loc.X < 0 || loc.Y < 0)
            {
                locOkay = false;
            }
            else if (loc.X + size.Width > Screen.PrimaryScreen.WorkingArea.Width)
            {
                locOkay = false;
            }
            else if (loc.Y + size.Height > Screen.PrimaryScreen.WorkingArea.Height)
            {
                locOkay = false;
            }
            else
            {
                locOkay = true;
            }
            return locOkay;
        }

        public static string GeometryToString(Form mainForm)
        {
            return mainForm.Location.X.ToString() + "|" +
                mainForm.Location.Y.ToString() + "|" +
                mainForm.Size.Width.ToString() + "|" +
                mainForm.Size.Height.ToString() + "|" +
                mainForm.WindowState.ToString();
        }

        public static void GeometryFromString(string thisWindowGeometry, Form formIn)
        {
            if (string.IsNullOrEmpty(thisWindowGeometry) == true)
            {
                return;
            }
            var numbers = thisWindowGeometry.Split('|');
            var windowString = numbers[4];
            if (windowString == "Normal")
            {
                var windowPoint = new Point(int.Parse(numbers[0]),
                    int.Parse(numbers[1]));
                var windowSize = new Size(int.Parse(numbers[2]),
                    int.Parse(numbers[3]));

                var locOkay = GeometryIsBizarreLocation(windowPoint, windowSize);
                var sizeOkay = GeometryIsBizarreSize(windowSize);

                if (locOkay == true && sizeOkay == true)
                {
                    formIn.Location = windowPoint;
                    formIn.Size = windowSize;
                    formIn.StartPosition = FormStartPosition.Manual;
                    formIn.WindowState = FormWindowState.Normal;
                }
                else if (sizeOkay == true)
                {
                    formIn.Size = windowSize;
                }
            }
            else if (windowString == "Maximized")
            {
                formIn.Location = new Point(100, 100);
                formIn.StartPosition = FormStartPosition.Manual;
                formIn.WindowState = FormWindowState.Maximized;
            }
        }
        #endregion

        private void MainForm_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            _isClosing = true;
            SimplePad.Properties.Settings.Default.WindowGeometry = GeometryToString(this);
            SimplePad.Properties.Settings.Default.OpenedFiles = new System.Collections.Specialized.StringDictionary();

            int i = 0;
            string[] files = new string[FilesManager.Files.Count];
            foreach (KeyValuePair<string, FileHandler> kvp in FilesManager.Files)
            {
                Properties.Settings.Default.OpenedFiles.Add(i.ToString(),kvp.Key);
                files[i] = kvp.Key;
                i++;
            }

            foreach (string file in files)
            {
                FilesManager.Files[file].Close();
            }
            SimplePad.Properties.Settings.Default.Save();
        }

        private void mnuSaveAs_Click(object sender, EventArgs e)
        {
            /*saveAsDialog.DefaultExt = (((SimplePad.TextEditor)(MainTabs.SelectedItem))).FileInfo.Extension;
            if (saveAsDialog.ShowDialog() == DialogResult.OK)
            {
                TextEditor.save((((SimplePad.TextEditor)(MainTabs.SelectedItem))), saveAsDialog.FileName);
            }*/
        }

        private void mnuView_Click(object sender, EventArgs e)
        {
            var tb = new Toolbar();
            tb.Show(MainDock, DockState.DockLeft);
        }

        private void mnuSeetings_Click(object sender, EventArgs e)
        {
            var f = new SettingsForm();
            f.Show();
        }
    }
}
